package com.cms.web.servlet;

import com.cms.pojo.Student;
import com.cms.pojo.Teacher;
import com.cms.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private AdminService service = new AdminService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户输入
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        int role = Integer.parseInt(request.getParameter("role"));

        boolean flag;
        if (role == 1) {
            // 学生注册
            Student student = new Student();
            student.setUsername(username);
            student.setPassword(password);
            student.setName(name);
            student.setEmail(email);
            student.setPhone(phone);

            // 调用service注册
            flag = service.Register(student, role);
        } else {
            // 教师注册
            Teacher teacher = new Teacher();
            teacher.setUsername(username);
            teacher.setPassword(password);
            teacher.setName(name);
            teacher.setEmail(email);
            teacher.setPhone(phone);

            // 调用service注册
            flag = service.Register(teacher, role);
        }

        // 判断注册成功与否
        if(flag) {
            // 注册成功，跳转登录
            request.setAttribute("register_msg", "注册成功，请登录");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
            // 注册失败
            request.setAttribute("register_msg", "注册失败，用户名已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
